<template>
	<div>
		<div class="head col-fl">
			<div class="col-main">
				<img class="head-logo col-fl" alt="logo" :src="navActive ? logoHei : logo" />
				<nav class="head-nav col-fl">
					<router-link class="head-li" v-for="(item,index) in navOptons" :key="index" :to="item.path">{{ item.label }}</router-link>
				</nav>
				<el-button class="head-btn" round @click="loginBtn" v-if="userInfos == ''">登录</el-button>
				<el-button class="head-btn1" round @click="registerBtn" v-if="userInfos == ''">注册</el-button>
				<!-- <el-switch @change="tabOpen" v-model="navActive" class="head-kg" style="--el-switch-on-color: #42b983; --el-switch-off-color: #666" /> -->
				<el-switch style="margin-left: 10px;" v-model="navActive" :active-icon="Moon" :inactive-icon="Sunny" inline-prompt @change="toggleDark" />
				<el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" :ellipsis="false" @select="handleSelect" v-if="userInfos != ''">
					<el-sub-menu>
						<template #title>{{userInfos.username != undefined ? userInfos.username : '-'}}</template>
						<!-- <el-menu-item index="2-1">item one</el-menu-item>
						<el-menu-item index="2-2">item two</el-menu-item> -->
						<el-menu-item index="2-3" @click="loginoutBtn">退出登录</el-menu-item>
					</el-sub-menu>
				</el-menu>
				<p class="head-right">{{ $getToDay }}备案号：赣ICP备2024046879号 ©www.liuwenbin.top </p>
			</div>
		</div>
		<div style="height: 60px; width: 100%;"></div>
		<el-dialog v-model="loginVisible" title="登录" width="500" :close-on-click-modal="false" @close="loginClose">
			<el-form ref="loginFormRef" :model="loginForm" :rules="loginRules">
				<el-form-item label="账号" :label-width="formLabelWidth" prop="username">
					<el-input v-model="loginForm.username" autocomplete="off" />
				</el-form-item>
				<el-form-item label="密码" :label-width="formLabelWidth" prop="password">
					<el-input v-model="loginForm.password" type="password" autocomplete="off" />
				</el-form-item>
			</el-form>
			<template #footer>
			<div class="dialog-footer">
				<el-button type="primary" @click="loginConfirm">登录</el-button>
			</div>
			</template>
		</el-dialog>
		<el-dialog v-model="dialogFormVisible" title="注册" width="500" :close-on-click-modal="false">
			<el-form ref="formRef" :model="form" :rules="rules">
				<el-form-item label="账号" :label-width="formLabelWidth" prop="username">
					<el-input v-model="form.username" autocomplete="off" />
				</el-form-item>
				<el-form-item label="密码" :label-width="formLabelWidth" prop="password">
					<el-input v-model="form.password" type="password" autocomplete="off" />
				</el-form-item>
				<el-form-item label="重复密码" :label-width="formLabelWidth" prop="confpwd">
					<el-input v-model="form.confpwd" type="password" autocomplete="off" />
				</el-form-item>
				<el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
					<el-input v-model="form.email" autocomplete="off" />
				</el-form-item>
				<el-form-item label="手机" :label-width="formLabelWidth">
					<el-input v-model="form.phone" autocomplete="off" />
				</el-form-item>
				<el-form-item label="性别" :label-width="formLabelWidth">
					<el-radio-group v-model="form.sex">
						<el-radio value="1" size="large">男</el-radio>
						<el-radio value="0" size="large">女</el-radio>
						<el-radio value="2" size="large">其他</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="出生日期" :label-width="formLabelWidth">
					<el-date-picker v-model="form.birth" format="YYYY/MM/DD" value-format="YYYY-MM-DD" type="date" placeholder="请输入出生日期" :shortcuts="shortcuts" size="default" :clearable="false"/>
				</el-form-item>
			</el-form>
			<template #footer>
			<div class="dialog-footer">
				<el-button @click="cancelBtn">取消</el-button>
				<el-button type="primary" @click="confirmBtn">确定</el-button>
			</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, getCurrentInstance } from 'vue';
import { Sunny, Moon } from "@element-plus/icons-vue";
import { ElForm, ElFormItem, ElInput, ElButton } from 'element-plus';
import { ElMessage } from 'element-plus'
import { useDark, useToggle } from "@vueuse/core";
import {
    userLogin,
    userInfo,
	userRegister,
	userLogout,
} from "@/request/api";
import logo from '@/assets/logo.png';
import logoHei from '@/assets/logo-hei.png';
const domStyle = document.documentElement.style;
const formLabelWidth = '140px'
const count = ref(0);
const data = reactive({
	navActive: useDark(),
	navOptons: [
		{value: 0, label: '首页', path: '/'},
		{value: 1, label: '关于', path: '/about'},
		{value: 2, label: 'AI助手', path: '/chart'},
		{value: 2, label: '组件&&模版', path: '/chart'},
	],
	form: {
		username: "",
		password: "",
		confpwd: "",
		email: "",
		phone: "",
		birth: new Date(),
		sex: "1"
	},
	rules: {
		username: [
			{ required: true, message: '请输入账号', trigger: 'blur' },
			{ min: 3, max: 20, message: '长度应为3到20', trigger: 'blur' },
		],
		password: [
			{ required: true, message: '请输入密码', trigger: 'blur' },
			{ min: 8, max: 20, message: '长度应为8到20', trigger: 'blur' },
		],
		confpwd: [
			{ required: true, message: '请输入重复密码', trigger: 'blur' },
			{ validator: (rule, value, callback) => {
				if (value !== form.value.password) {
					callback(new Error('两次输入的密码不一致'));
				} else {
					callback();
				}
			}, trigger: 'blur' },
		],
		email: [
			{ required: true, message: '请输入邮箱地址', trigger: 'blur' },
			{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
		]
	},
	dialogFormVisible: false,
	shortcuts: [
		{ text: '今天', value: new Date() },
		{ text: '昨天',
			value: () => {
				const date = new Date()
				date.setTime(date.getTime() - 3600 * 1000 * 24)
				return date
			},
		},
		{
			text: '一周前',
				value: () => {
				const date = new Date()
				date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
				return date
			},
		},
	],
	loginVisible: false,
	loginForm: {
		username: "",
		password: "",
	},
	loginRules: {
		username: [
			{ required: true, message: '请输入账号', trigger: 'blur' }
		],
		password: [
			{ required: true, message: '请输入密码', trigger: 'blur' }
		]
	},
	userInfos: '',
})
const { 
	navActive, 
	navOptons,
	dialogFormVisible,
	form,
	rules,
	shortcuts,
	loginVisible,
	loginForm,
	loginRules,
	userInfos,
} = toRefs(data);
// const disabledDate = (time) => {
//   return time.getTime() < Date.now() - 86400000; // 禁用所有过去的时间，减去一天的毫秒数
// };
const formRef = ref(null);
const instance = getCurrentInstance();  
const getToDay = ref(instance.appContext.config.globalProperties.$getToDay);
const loginFormRef = ref(null);
onMounted(() => {
	console.log("信息",getToDay)
	if (localStorage.getItem("userInfos")) {
		data.userInfos = JSON.parse(localStorage.getItem("userInfos"));
	}
	data.form.birth = getToDay;
	toggleDark()
});
// const toggleDark = useToggle(data.navActive);
function checkVal(val,col1,col2) {
	domStyle.setProperty(val, data.navActive ? col1 : col2);
}
function toggleDark() {
	useToggle(data.navActive);
	checkVal('--bwsz-all-bg','#111111','#f4f8fd');
	checkVal('--bwsz-nav-bg','#191919','#fff');
	checkVal('--bwsz-nav-li-color','#bfbfbf','#2c3e50');
	checkVal('--el-color-primary', '#42b983', '#42b983')
}

function registerBtn() { // 注册
	data.dialogFormVisible = true;
}
function loginBtn() { // 登录
	console.log("测试")
	data.loginVisible = true;
}
function cancelBtn() { // 取消
	data.dialogFormVisible = false;
	data.form = {
		username: "",
		password: "",
		confpwd: "",
		email: "",
		phone: "",
		birth: getToDay,
		sex: "1"
	}
	formRef.value.resetFields()
}
function confirmBtn() { // 确定
	let param = JSON.parse(JSON.stringify(data.form))
	delete param.confpwd;
	// console.log(param)
	formRef.value.validate((valid) => {
		if (valid) {
			userRegister(param).then(res => {
				console.log(res)
				if (res.code == 200) {
					ElMessage({
						message: '注册成功',
						type: 'success',
					})
					data.dialogFormVisible = false;
				} else {
					ElMessage({
						message: res.code + ':注册失败',
						type: 'error',
					})
				}
			})
		}
	});
}
function loginConfirm() { // 登录-确定
	userLogin({
		username: data.loginForm.username,
		password: data.loginForm.password,
	}).then(res => {
		if (res.code == 200) {
			ElMessage({
				message: '登录成功',
				type: 'success',
			})
			data.loginVisible = false;
			localStorage.setItem('token', res.data);
			userInfo({}).then(res1 => {
				console.log("信息",res1)
				localStorage.setItem("userInfos", JSON.stringify(res1))
				data.userInfos = res1;
			})
		} else {
			ElMessage({
				message: res.code + ':登录失败',
				type: 'error',
			})
		}
	})
}
function loginClose() { // 登录-关闭
	data.loginVisible = false;
	data.loginForm = {
		username: "",
		password: "",
	}
	loginFormRef.value.resetFields()
}
function loginoutBtn() { // 退出登录
	userLogout().then(res => {
		if (res.code == 200) {
			ElMessage({
				message: '退出登录成功',
				type: 'success',
			})
			localStorage.clear();
			location.reload();
		} else {
			ElMessage({
				message: res.code + ':退出登录失败',
				type: 'error',
			})
		}
	})
}
</script>

<style lang="less">
	.el-menu--horizontal.el-menu {
		height: 25px;
		display: inline-block;
		border-bottom: 0px solid #ddd;
	}
	.el-sub-menu {
		height: 25px;
	}
</style>